from flask import Blueprint, render_template, request, current_app
from app.models import Activity, Course, Organization

main_bp = Blueprint('main', __name__)

@main_bp.route('/')
def index():
    # 获取精选活动、课程和机构
    featured_activities = Activity.query.filter_by(is_featured=True).order_by(
        Activity.created_at.desc()).limit(3).all()
    featured_courses = Course.query.filter_by(is_featured=True).order_by(
        Course.created_at.desc()).limit(3).all()
    partner_orgs = Organization.query.filter_by(is_partner=True).order_by(
        Organization.created_at.desc()).limit(4).all()
    
    return render_template('main/index.html', 
                         activities=featured_activities,
                         courses=featured_courses,
                         orgs=partner_orgs)

@main_bp.route('/activities')
def activities():
    page = request.args.get('page', 1, type=int)
    region = request.args.get('region', 'all')
    
    query = Activity.query
    
    if region != 'all':
        query = query.filter_by(region=region)
    
    activities = query.order_by(Activity.start_time.desc()).paginate(
        page=page, per_page=current_app.config['ITEMS_PER_PAGE'], error_out=False)
    
    return render_template('main/activities.html', activities=activities, region=region)

@main_bp.route('/courses')
def courses():
    page = request.args.get('page', 1, type=int)
    difficulty = request.args.get('difficulty', 'all')
    
    query = Course.query.filter_by(status='published')
    
    if difficulty != 'all':
        query = query.filter_by(difficulty=difficulty)
    
    courses = query.order_by(Course.created_at.desc()).paginate(
        page=page, per_page=current_app.config['ITEMS_PER_PAGE'], error_out=False)
    
    return render_template('main/courses.html', courses=courses, difficulty=difficulty)

@main_bp.route('/organizations')
def organizations():
    page = request.args.get('page', 1, type=int)
    region = request.args.get('region', 'all')
    
    query = Organization.query
    
    if region != 'all':
        query = query.filter_by(region=region)
    
    orgs = query.order_by(Organization.name.asc()).paginate(
        page=page, per_page=current_app.config['ITEMS_PER_PAGE'], error_out=False)
    
    return render_template('main/organizations.html', orgs=orgs, region=region)

@main_bp.route('/activity/<int:id>')
def activity_detail(id):
    activity = Activity.query.get_or_404(id)
    return render_template('main/activity_detail.html', activity=activity)

@main_bp.route('/course/<int:id>')
def course_detail(id):
    course = Course.query.get_or_404(id)
    return render_template('main/course_detail.html', course=course)

@main_bp.route('/organization/<int:id>')
def organization_detail(id):
    org = Organization.query.get_or_404(id)
    return render_template('main/organization_detail.html', org=org)